package com.xicheng.immerse.viewmodel

import android.app.Application
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.immerse.ext.ILogger
import com.immerse.ext.logD
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import com.xicheng.immerse.viewmodel.uistate.UiState
import com.xicheng.immerse.viewmodel.intent.ViewIntent
import com.xicheng.immerse.MainActivity
import java.util.*

/**
 * 负责[MainActivity]的UI数据
 */
class MainViewModel(application: Application) : AndroidViewModel(application), ILogger {
    companion object {
        private const val TAG = "ImmerseViewModel"
    }

    override val tag: String = TAG

    private val calendar by lazy { GregorianCalendar() }

    /**
     * 当前页面展示的数据
     */
    val state: State<UiState> get() = _state
    private val _state = mutableStateOf<UiState>(UiState.Loading)

    init {
        viewModelScope.launch(Dispatchers.Default) { initState() }
    }

    /**
     * UI层响应事件，通过此接口发送Intent，触发数据更新
     * @param intent UI层的意图
     */
    fun sendIntent(intent: ViewIntent) {
        viewModelScope.launch(Dispatchers.Main.immediate) {
            when (intent) {
                is ViewIntent.DayClickIntent -> {
                    _state.value = _state.value.consumeClickIntent(intent.day)
                    logD { "sendIntent: day click, ${intent.day}" }
                }

                else -> {
                    logD { "sendIntent: unknown intent:$intent" }
                }
            }
        }
    }

    private suspend fun UiState.consumeClickIntent(day: Day): UiState =
        withContext(Dispatchers.Default) {
            UiState.Loading
        }

    private suspend fun initState() {
        calendar
    }
}